package audit

import (
	"counter-help/admin/server/global"
	"counter-help/admin/server/model/audit"
	auditReq "counter-help/admin/server/model/audit/response"
	"counter-help/admin/server/model/customer"
	"errors"
	"gorm.io/gorm"
)

type UserIdentityService struct{}

// CreateIdentity 创建身份认证信息

func (service *UserIdentityService) CreateOrUpdateIdentity(identity audit.UserIdentity) error {
	var existingIdentity audit.UserIdentity
	// 检查是否已存在此用户的身份认证记录
	if err := global.GVA_DB.Where("user_id = ?", identity.UserID).First(&existingIdentity).Error; err == nil {
		// 如果记录存在，逐字段检查并更新
		if identity.RealName != "" {
			existingIdentity.RealName = identity.RealName
		}
		if identity.DocumentType != "" {
			existingIdentity.DocumentType = identity.DocumentType
		}
		if identity.DocumentNumber != "" {
			existingIdentity.DocumentNumber = identity.DocumentNumber
		}
		if identity.FrontImagePath != "" {
			existingIdentity.FrontImagePath = identity.FrontImagePath
		}
		if identity.BackImagePath != "" {
			existingIdentity.BackImagePath = identity.BackImagePath
		}
		existingIdentity.IsReviewed = false
		return global.GVA_DB.Save(&existingIdentity).Error
	} else if errors.Is(err, gorm.ErrRecordNotFound) {
		// 如果记录不存在，执行创建操作
		return global.GVA_DB.Create(&identity).Error
	} else {
		// 处理其他错误
		return err
	}
}

// UpdateIdentity 更新身份认证信息
func (service *UserIdentityService) UpdateIdentity(identity audit.UserIdentity) error {
	return global.GVA_DB.Model(&audit.UserIdentity{}).
		Where("user_id = ?", identity.UserID).
		Updates(identity).Error
}

// GetIdentityByUserID 根据用户 ID 获取身份认证信息
func (service *UserIdentityService) GetIdentityByUserID(userID uint) (audit.UserIdentity, error) {
	var identity audit.UserIdentity
	err := global.GVA_DB.Where("user_id = ?", userID).First(&identity).Error
	return identity, err
}

// DeleteIdentity 删除身份认证信息
func (service *UserIdentityService) DeleteIdentity(userID uint) error {
	return global.GVA_DB.Where("user_id = ?", userID).Delete(&audit.UserIdentity{}).Error
}

// UpdateIdentityStatus 更新身份认证的审核状态
func (service *UserIdentityService) UpdateIdentityStatus(userID uint, isReviewed, isApproved bool, rejectionReason string) error {
	return global.GVA_DB.Model(&audit.UserIdentity{}).Where("user_id = ?", userID).Updates(map[string]interface{}{
		"is_reviewed":      isReviewed,
		"is_approved":      isApproved,
		"rejection_reason": rejectionReason,
	}).Error
}

// GetPendingIdentities 获取所有未审核的身份认证记录，并手动关联用户信息
func (s *UserIdentityService) GetPendingIdentities() ([]auditReq.UserIdentityResponse, error) {
	var pendingIdentities []audit.UserIdentity
	err := global.GVA_DB.Model(&audit.UserIdentity{}).
		Where("is_reviewed = ?", false).
		Find(&pendingIdentities).Error
	if err != nil {
		return nil, err
	}

	var responses []auditReq.UserIdentityResponse
	for _, identity := range pendingIdentities {
		var user customer.CusUser
		if err := global.GVA_DB.Where("id = ?", identity.UserID).First(&user).Error; err != nil {
			return nil, err
		}
		responses = append(responses, convertUserIdentityToResponse(identity, user))
	}
	return responses, nil
}

// GetApprovedIdentities 获取所有已审核的身份认证记录，并手动关联用户信息
func (s *UserIdentityService) GetApprovedIdentities() ([]auditReq.UserIdentityResponse, error) {
	var approvedIdentities []audit.UserIdentity
	err := global.GVA_DB.
		Where("is_reviewed = ? ", true).
		Find(&approvedIdentities).Error
	if err != nil {
		return nil, err
	}

	var responses []auditReq.UserIdentityResponse
	for _, identity := range approvedIdentities {
		var user customer.CusUser
		if err := global.GVA_DB.Where("id = ?", identity.UserID).First(&user).Error; err != nil {
			return nil, err
		}
		responses = append(responses, convertUserIdentityToResponse(identity, user))
	}
	return responses, nil
}

// convertUserIdentityToResponse 转换为包含用户信息的响应结构体
func convertUserIdentityToResponse(identity audit.UserIdentity, user customer.CusUser) auditReq.UserIdentityResponse {
	return auditReq.UserIdentityResponse{
		UserIdentity: identity,
		User:         user,
	}
}
